/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package l1j.server.server.model;

import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.Config;
import l1j.server.Thread.GeneralThreadPool;
import l1j.server.server.templates.L1Npc;
import l1j.server.server.utils.Random;

public class L1BossSpawn extends L1Spawn {
	private class SpawnTask implements Runnable {
		private final int _spawnNumber;
		private final int _objectId;

		private SpawnTask(final int spawnNumber, final int objectId) {
			this._spawnNumber = spawnNumber;
			this._objectId = objectId;
		}

		// @Override
		@Override
		public void run() {
			L1BossSpawn.this.doSpawn(this._spawnNumber, this._objectId);
		}
	}

	private static Logger _log = Logger.getLogger(L1BossSpawn.class.getName());

	private int _spawnCount;

	private String _cycleType;

	private int _percentage;

	private L1BossCycle _cycle;

	private Calendar _activeSpawnTime;

	public L1BossSpawn(final L1Npc mobTemplate) {
		super(mobTemplate);
	}

	// 確率計算して次の出現時間を算出
	private Calendar calcNextSpawnTime(Calendar cal) {
		do {
			cal = this._cycle.nextSpawnTime(cal);
		} while (!(this._percentage > Random.nextInt(100)));
		return cal;
	}

	/**
	 * SpawnTaskを起動する。
	 *
	 * @param spawnNumber
	 *            L1Spawnで管理されている番号。ホームポイントが無ければ何を指定しても良い。
	 */
	@Override
	public void executeSpawnTask(final int spawnNumber, final int objectId) {
		// 遞減計數，並檢查是否全部死亡
		if (this.subAndGetCount() != 0) {
			return; // 尚未全部死亡
		}
		// 對應前回出現時間，並計算下一次出現時間
		Calendar spawnTime;
		final Calendar now = Calendar.getInstance(); // 現在
		final Calendar latestStart = this._cycle.getLatestStartTime(now); // 現時刻に対する最近の周期の開始時間

		final Calendar activeStart = this._cycle.getSpawnStartTime(this._activeSpawnTime); // アクティブだった周期の開始時間
		// アクティブだった周期の開始時間 >= 最近の周期開始時間の場合、次の出現
		if (!activeStart.before(latestStart)) {
			spawnTime = this.calcNextSpawnTime(activeStart);
		} else {
			// アクティブだった周期の開始時間 < 最近の周期開始時間の場合は、最近の周期で出現
			// わかりづらいが確率計算する為に、無理やりcalcNextSpawnTimeを通している。
			latestStart.add(Calendar.SECOND, -1);
			spawnTime = this.calcNextSpawnTime(this._cycle.getLatestStartTime(latestStart));
		}
		this.spawnBoss(spawnTime, objectId);
	}

	@Override
	public void init() {
		if (this._percentage <= 0) {
			return;
		}
		this._cycle = L1BossCycle.getBossCycle(this._cycleType);
		if (this._cycle == null) {
			throw new RuntimeException(this._cycleType + " not found");
		}
		final Calendar now = Calendar.getInstance();
		// 出現時間
		Calendar spawnTime;
		if (Config.INIT_BOSS_SPAWN && this._percentage > Random.nextInt(100)) {
			spawnTime = this._cycle.calcSpawnTime(now);

		} else {
			spawnTime = this.calcNextSpawnTime(now);
		}
		this.spawnBoss(spawnTime, 0);
	}

	public void setCycleType(final String type) {
		this._cycleType = type;
	}


	public void setPercentage(final int percentage) {
		this._percentage = percentage;
	}

	// 指定された時間でボス出現をスケジュール
	private void spawnBoss(final Calendar spawnTime, final int objectId) {
		// 今回の出現時間を保存しておく。再出現時に使用。
		this._activeSpawnTime = spawnTime;
		final long delay = spawnTime.getTimeInMillis() - System.currentTimeMillis();

		int cnt = this._spawnCount;
		this._spawnCount = this.getAmount();
		while (cnt < this.getAmount()) {
			cnt++;
			GeneralThreadPool.getInstance().schedule(new SpawnTask(0, objectId), delay);
		}
		_log.log(Level.FINE, this.toString());
	}

	private synchronized int subAndGetCount() {
		return --this._spawnCount;
	}

	/**
	 * 現在アクティブなボスに対する周期と出現時間を表す。
	 */
	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append("[MOB]npcid:" + this.getNpcId());
		builder.append(" name:" + this.getName());
		builder.append("[Type]" + this._cycle.getName());
		builder.append("[目前的週期]");
		builder.append(this._cycle.getSpawnStartTime(this._activeSpawnTime).getTime());
		builder.append(" - ");
		builder.append(this._cycle.getSpawnEndTime(this._activeSpawnTime).getTime());
		builder.append("[出現時間]");
		builder.append(this._activeSpawnTime.getTime());
		return builder.toString();
	}
}
